const Base = think.require('src/common/yy/mongoose/Mongoose')
module.exports = class extends Base {
  schema () {
    return {
      nick_name: { type: String, default: '' }, // 名称
      head_img: { type: String, default: '' }, // 头像
      service_type_info: {type: Number, default: 0}, // 授权方公众号类型，0代表订阅号，1代表由历史老帐号升级后的订阅号，2代表服务号
      verify_type_info: {type: Number, default: 0}, // 授权方认证类型，-1代表未认证，0代表微信认证，1代表新浪微博认证，2代表腾讯微博认证，3代表已资质认证通过但还未通过名称认证，4代表已资质认证通过、还未通过名称认证，但通过了新浪微博认证，5代表已资质认证通过、还未通过名称认证，但通过了腾讯微博认证
      user_name: { type: String, default: '' }, // 授权方公众号的原始ID
      alias: { type: String, default: '' }, // 授权方公众号所设置的微信号，可能为空
      business_info: { type: Object }, // 用以了解功能的开通状况 数组
      qrcode_url: { type: String, default: '' },
      appid: { type: String, default: '' },
      func_info: { type: Array, default: [] }, // 权限
      account_id: {type: Number, default: 0},
      refresh_token: {type: String, default: ''}, // 公众号刷新token
      auth_time: {type: Number, default: 0},
      authorized: {type: Number, default: 0}// 授权状态
    }
  }
  tofuncInfo (d) {
    const data = []
    d.map((v) => {
      data.push(v.funcscope_category.id)
    })
    return data
  }
  async saveAuthorizer (d) {
    const data = Object.assign({}, d.authorizer_info, d.authorization_info)
    const insertData = {
      appid: data.authorizer_appid,
      nick_name: data.nick_name,
      head_img: data.head_img,
      service_type_info: data.service_type_info.id,
      verify_type_info: data.verify_type_info.id,
      user_name: data.user_name,
      alias: data.alias,
      qrcode_url: data.qrcode_url,
      business_info: data.business_info,
      func_info: this.tofuncInfo(data.func_info),
      refresh_token: data.authorizer_refresh_token,
      authorized: 1
    }
    const map = {appid: data.authorizer_appid}
    const count = await this.where(map).count()
    let insertId = 0
    if (count) {
      await this.where(map).update(insertData)
      const {id} = await this.where(map).field('id').find()
      insertId = id
    } else {
      insertId = await this.add(insertData)
    }
    return insertId
  }
  /**
     * @param oauth 微信推送过来的更新 删除 添加公众号消息
     * @param status
     */
  async refreshStatus (oauth = {}, status = 1) {
    await this.where({appid: oauth.AuthorizerAppid}).update({authorized: status})
    const id = await this.where({appid: oauth.AuthorizerAppid}).field('id').find()
    yy.log.debug('refreshStatus', id)
    await think.cache(`access_token_${id}`)
  }
  /**
   * 同步远程列表
   * @param {a} v
   */
  async sync (v) {
    if (v.authorizer_appid) {
      const data = {
        appid: v.authorizer_appid,
        refresh_token: v.refresh_token,
        auth_time: v.auth_time

      }
      const check = await this.where({appid: v.authorizer_appid}).count()
      if (check > 0) {
        await this.where({appid: v.authorizer_appid}).update(data)
      } else {
        await this.add(data)
      }
    }
  }
}
